package com.tianma315.admin.material.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.check.service.CheckRecordService;
import com.tianma315.admin.check.vo.CheckRecordArrtVO;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.material.VO.PurchaseAndArrtVO;
import com.tianma315.admin.material.VO.PurchaseAndCheckAttrVO;
import com.tianma315.admin.material.VO.PurchaseVO;
import com.tianma315.admin.material.domain.MaterialDO;
import com.tianma315.admin.material.service.MaterialService;
import com.tianma315.admin.oss.domain.FileDO;
import com.tianma315.admin.oss.service.FileService;
import com.tianma315.admin.supplier.domain.SupplierDO;
import com.tianma315.admin.supplier.service.SupplierService;
import com.tianma315.admin.util.CellUtil;
import com.tianma315.admin.util.HiddenSheetUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.material.dao.PurchaseDao;
import com.tianma315.admin.material.domain.PurchaseDO;
import com.tianma315.admin.material.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 原材料进库表
 * </pre>
 * <small> 2019-05-25 15:23:18 | Aron</small>
 */
@Service
public class PurchaseServiceImpl extends CoreServiceImpl<PurchaseDao, PurchaseDO> implements PurchaseService {

    @Autowired
    private PurchaseDao purchaseDao;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private FileService sysFileService;

    @Autowired
    private CheckRecordService checkRecordService;

    @Override
    public Page<PurchaseVO> getPurchaseVOPage(Integer pageNumber, Integer pageSize, String searchName) {
        Page<PurchaseVO> page = new Page(pageNumber,pageSize);
        List<PurchaseVO> purchaseVOList = purchaseDao.getPurchaseVO(page,searchName);
        page.setRecords(purchaseVOList);
        return page;
    }

    @Override
    public Boolean addPurchase(PurchaseDO purchaseDO) {
        purchaseDO.setState(0);
        return insert(purchaseDO);
    }

    @Override
    public Boolean deletePurchase(Integer id) {
        PurchaseDO purchaseDO = new PurchaseDO();
        purchaseDO.setState(1);
        purchaseDO.setPurchaseId(id);
        return updateById(purchaseDO);
    }

    @Override
    public List<PurchaseAndArrtVO> statisticsMaterialAllTable(List<Integer> materialIds, Date beginDate, Date endDate) {
        List<PurchaseAndArrtVO> list = purchaseDao.statisticsMaterialAllTable(materialIds,beginDate,endDate);
        List<PurchaseAndArrtVO> resultList = new ArrayList<>();
        Map<Integer,PurchaseAndArrtVO> map  =new HashMap<>();
        //进行统计检测的次数，及合并同一种原材料的检测记录
        Integer count = 1;//次数
        for (PurchaseAndArrtVO p:list) {
           PurchaseAndArrtVO po = map.get(p.getMaterialId());
           if (po == null){
               p.setCountNum(count);
               po = p;
           }else{
               po.setCountNum(po.getCountNum()+1);
               po.getRecordArrtVOS().addAll(p.getRecordArrtVOS());
           }
           map.put(p.getMaterialId(),po);
        }

        List<PurchaseAndArrtVO> purchaseAndArrtVOList = new ArrayList<>();
        for(PurchaseAndArrtVO p :map.values()){
            purchaseAndArrtVOList.add(p);
        }
        return purchaseAndArrtVOList;
    }

    @Override
    public List<PurchaseAndArrtVO> statisticsMaterialTable( Page page,List<Integer> materialIds,Date beginDate, Date endDate) {
        return purchaseDao.statisticsMaterialTable(page,materialIds,beginDate,endDate);
    }

    @Override
    public HSSFWorkbook exportPurchase() {
        String[] title = {"入库日期","供应商","原料名称","数量","仓库","采购人","批次"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("原材料记录模板");

//        sheet.addMergedRegion(new CellRangeAddress(0,0,0,8));//第一行第一列开始，跨8列
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("原材料记录模板（红色标识列为必填）");
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);

        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0; i<title.length; i++){
            //下标小于7是必填列
            if (i < 7){
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
            }else{
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(defaultStyle);
            }
        }

        List<MaterialDO> materialDOS = materialService.getMaterialList();
        List<String> materialList = materialDOS.stream().map(item -> item.getMaterialName()).collect(Collectors.toList());
        String[] materialNameArr = materialList.toArray(new String[materialList.size()]);

        String materialHiddenSheet = "materialHidden";
        Integer cellNum = 2;
        Integer startRow = 2; // 开始行
        Integer endRow = 10000; // 结束行

        HiddenSheetUtil.initHiddenSheet(materialHiddenSheet,wb,cellNum,startRow,endRow,materialNameArr);
        //设置设备类型为下拉框选项
        DVConstraint constraint = DVConstraint.createFormulaListConstraint(materialHiddenSheet);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(startRow,
                endRow, cellNum, cellNum);
        HSSFDataValidation materialData = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(materialData);
        wb.setSheetHidden(1, true);


        List<SupplierDO> supplierDOS = supplierService.getSupplierList();
        List<String> supplierList = supplierDOS.stream().map(item -> item.getSupplierName()).collect(Collectors.toList());
        String[] supplierListNameArr = supplierList.toArray(new String[supplierList.size()]);


        String supplierHiddenSheet = "supplierHidden";
        Integer supplierCellNum = 1;
        Integer supplierStartRow = 2; // 开始行
        Integer supplierEndRow = 10000; // 结束行
        HiddenSheetUtil.initHiddenSheet(supplierHiddenSheet,wb,supplierCellNum,supplierStartRow,supplierEndRow,supplierListNameArr);
        //设置设备类型为下拉框选项
        DVConstraint supplierConstraint = DVConstraint.createFormulaListConstraint(supplierHiddenSheet);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList supplierRegions = new CellRangeAddressList(supplierStartRow,
                supplierEndRow, supplierCellNum, supplierCellNum);
        HSSFDataValidation supplierData = new HSSFDataValidation(
                supplierRegions, supplierConstraint);
        sheet.addValidationData(supplierData);
        wb.setSheetHidden(2, true);
        return wb;
    }

    @Override
    @Transactional
    public void importPurchase(MultipartFile file, Long userId) {
        Boolean flag = CellUtil.isExcel(file.getOriginalFilename());
        if (!flag){
            throw new MessageException("只支持Excel文件");
        }

        List<MaterialDO> materialDOList = materialService.getMaterialList();
        List<SupplierDO> supplierDOList = supplierService.getSupplierList();

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //前2行都不是内容，所以从2开始
            for (int i = 2; i <= rowNum; i++) {
                Row row = sheet.getRow(i);
                short num = row.getLastCellNum();
                PurchaseDO purchaseDO = new PurchaseDO();
                purchaseDO.setCreateBy(userId);
                purchaseDO.setCreateDate(Calendar.getInstance().getTime());
                purchaseDO.setState(0);

                //设置入库时间
                Cell inStockDate = row.getCell(0);
                if (inStockDate!=null){
                    inStockDate.setCellType(CellType.NUMERIC);
//                    inStockDate.setCellType(CellType.);
                    purchaseDO.setInStockDate(inStockDate.getDateCellValue());
                }

                //设置供应商
                Cell supplierCell = row.getCell(1);
                if (CellUtil.isCellEmpty(supplierCell)){
                    throw new MessageException("供应商不能空");
                }
                List<SupplierDO> supplierFilterResult = supplierDOList.stream()
                        .filter(item -> item.getSupplierName().equals(supplierCell.getStringCellValue()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(supplierFilterResult)){
                    throw new MessageException(supplierCell.getStringCellValue()+"未找到");
                }else{
                    purchaseDO.setSupplierId(supplierFilterResult.get(0).getSupplierId());
                }


                //设置原料id
                Cell materialCell = row.getCell(2);
                if (CellUtil.isCellEmpty(materialCell)){
                    throw new MessageException("原料不能为空");
                }
                List<MaterialDO> materialFilterResult = materialDOList.stream()
                        .filter(item -> item.getMaterialName().equals(materialCell.getStringCellValue()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(materialFilterResult)){
                    throw new MessageException(materialCell.getStringCellValue()+"未找到");
                }else{
                    purchaseDO.setMaterialId(materialFilterResult.get(0).getMaterialId());
                }


                //设置数量
                Cell numberCell = row.getCell(3);
                Integer number = 0;
                if (!CellUtil.isCellEmpty(numberCell)){
                    number = Integer.parseInt(numberCell.getStringCellValue());
                }
                purchaseDO.setNumber(number);

                //设置仓库
                Cell stockName = row.getCell(4);
                if (stockName != null ){
                    stockName.setCellType(CellType.STRING);
                    purchaseDO.setStockName(stockName.getStringCellValue());
                }

                //设置采购人
                Cell purchaseCell = row.getCell(5);
                if (CellUtil.isCellEmpty(purchaseCell)){
                    throw new MessageException("采购人不能为空");
                }
                purchaseDO.setPurchaser(purchaseCell.getStringCellValue());

                //设置批次
                Cell purchaseNoCell = row.getCell(6);
                if (CellUtil.isCellEmpty(purchaseNoCell)){
                    throw new MessageException("批次不能为空");
                }
                purchaseDO.setPurchaseNo(purchaseNoCell.getStringCellValue());

                //设置生产日期
//                Cell dateOfProduction = row.getCell(7);
//                if (dateOfProduction != null ){
//                    purchaseDO.setDateOfProduction(dateOfProduction.getDateCellValue());
//                }

                //设置入库标识
//                Cell identifierCell = row.getCell(8);
//                if (identifierCell != null ){
//                    identifierCell.setCellType(CellType.STRING);
//                    purchaseDO.setIdentifier(identifierCell.getStringCellValue());
//                }



                insert(purchaseDO);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public List<PurchaseAndCheckAttrVO> getPurchaseByBatchAndMaterialId(Integer materialId, String batch) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("material_id",materialId);
        wrapper.eq("purchase_no",batch);
        wrapper.eq("state",0);
        List<PurchaseDO> purchaseDOS = selectList(wrapper);

        List<PurchaseAndCheckAttrVO> result = new ArrayList<>();
        for (int i = 0; i < purchaseDOS.size(); i++) {
            PurchaseAndCheckAttrVO purchaseVO = new PurchaseAndCheckAttrVO();
            PurchaseDO purchaseDO = purchaseDOS.get(i);
            SupplierDO supplierDO = supplierService.selectById(purchaseDO.getSupplierId());
            BeanUtils.copyProperties(purchaseDO,purchaseVO);
            purchaseVO.setLinkman(supplierDO.getLinkman());
            purchaseVO.setTel(supplierDO.getTel());
            purchaseVO.setSupplierName(supplierDO.getSupplierName());
            CheckRecordArrtVO checkRecordArrtVO = checkRecordService.getCheckRecordArrtVO2(purchaseDO.getPurchaseId());
            purchaseVO.setCheckRecordArrtVO(checkRecordArrtVO);
            MaterialDO materialDO = materialService.selectById(purchaseVO.getMaterialId());
            purchaseVO.setMaterialName(materialDO.getMaterialName());
            purchaseVO.setShelflife(materialDO.getShelflife());

            result.add(purchaseVO);
        }

        return result;
    }

    @Override
    public void insertImg(HttpServletRequest request, PurchaseDO purchaseDO) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        //转换为集合
        Set<Map.Entry<String, MultipartFile>> eSet = fileMap.entrySet();
        String url = "";
        //遍历集合元素
        for (Map.Entry<String, MultipartFile> entry : eSet) {
            //获取图片文件对象
            MultipartFile mFile = entry.getValue();
            try {
              url = sysFileService.upload(mFile.getBytes(), mFile.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将地址更新到数据库中去
        PurchaseDO purchaseDO1 = selectById(purchaseDO);
        String reportImg = purchaseDO1.getReportImg();
        if (reportImg != null&& !reportImg.equals("")){
            reportImg=reportImg+','+url;
        }else{
            reportImg = url;
        }
        purchaseDO.setReportImg(reportImg);
        updateById(purchaseDO);
    }

    @Override
    public boolean updatePurById(PurchaseDO purchaseDO) {
        if (purchaseDao.updatePurById(purchaseDO)==1)
          return true;
        return false;
    }
}
